// pages/pubComment/index.js
import { request } from '../../request/index'

Page({
  uploadFile: function () {

    var that = this
    wx.chooseImage({
      count: 9,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        that.setData({
          img: res.tempFilePaths
        })
      }
    })
  },
  input: function (e) {
    this.setData({
      content: e.detail.value
    })
  },
  star: function (e) {
    this.setData({ star: parseInt(e.currentTarget.dataset.i) })
  },
  send: function () {
    var app = getApp()
    var data = {
      userId: app.globalData.userId,
      avatar: app.globalData.avatar,
      coachId: this.data.coachId === "" ? "" : this.data.coachId,
      termId: this.data.termId === "" ? "" : parseInt(this.data.termId),
      contents: this.data.content,
      imgUrl: '',
      star: this.data.star
    }
    request({ url: app.globalData.root + 'api/addComment', method: 'POST', data: data, dataType: 'json' }).then((res) => {
      this.data.img.forEach((item, index) => {
        wx.uploadFile({
          url: app.globalData.root + 'api/commentUpload', //仅为示例，非真实的接口地址
          filePath: item,
          name: '图片',
          formData: {
            'id': '' + res.data.id
          },
          success(res) {
          },
          complete() {
            wx.showToast({
              title: '评论成功',
              icon: 'success',
              duration: 3000,
              complete() {
                var timeId = setTimeout(() => {
                  clearTimeout(timeId)
                  wx.navigateBack({
                    delta: 1
                  })
                }, 2000);
              }
            })
          }
        })
      })

      wx.navigateBack()

    })

  },
  /**
   * 页面的初始数据
   */
  data: {
    img: [],
    content: '',
    coachId: '',
    termId: '',
    star: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.coachId) {
      this.setData({
        coachId: options.coachId,
      })
    } else {
      this.setData({
        termId: options.termId,
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})